<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Common\WechatHandler;
use App\Models\Member\User;
use App\Models\Member\PayConfig;

class WechatController extends Controller
{
    // 微信公众号消息事件
    public function event(Request $request)
    {
        $storeId = $request['store_id'];
        if (empty($storeId)) return false;

        if (!WechatHandler::checkStore($storeId)) return false;

        // 绑定公众号基础域名
        if (!empty($request['echostr']))
            return WechatHandler::bindHost($request);

        $data = WechatHandler::xmlToArr($request);
        if (empty($data)) return false;

        $data['store_id'] = $storeId;
        if ($data['MsgType'] == 'event') {
            // event 包含subscribe 和 unsubscribe
            $e = $data['Event'];
            $this->$e($data);
        }

        if ($data['MsgType'] == 'text') {
            $this->text($data);
        }

    }

    // 关注事件逻辑
    private function subscribe($data)
    {
        WechatHandler::wxLogin($data['FromUserName'], $data['store_id'], 'subscribe');
    }

    // 取消关注逻辑
    private function unsubscribe($data)
    {
        $user = new User;
        $user->unsubscribe($data['FromUserName'], $data['store_id']);
    }

    // 收到用户发送的消息
    private function text($data)
    {
    }

    // 微信授权获取code
    public function getOauthUrl(Request $request)
    {
        $storeId = $request['storeId'];
        $redirectType = $request['redirectType'];
        $data = WechatHandler::getOauthUrl($storeId, $redirectType);

        return self::successClient($data);
    }

    public function wxLogin(Request $request)
    {
        $storeId = $request['storeId'];
        $code = $request['code'];

        $data = WechatHandler::wxLogin('', $storeId, 'login', $code);
        return self::successClient($data);
    }

    public function initSdk(Request $request)
    {
        $data = WechatHandler::initSdk($request['url']);
        return self::successClient($data);
    }
    // 生成店铺access——token
    public function getAccessToken(Request $request)
    {
        $storeId = $request['storeId'];
        $wxConfig = PayConfig::where('store_id', $storeId)->first()->toArray();
        $accessToken = WechatHandler::getAccessToken($storeId, $wxConfig);
        return $accessToken;
    }
}
